package oj_leetcode;

import java.util.*;

public class FourSum {
    public static void main(String[] args) {
        System.out.println(new FourSum().fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0));
    }

    public List<List<Integer>> fourSum(int[] nums, int target) {
        if (nums.length < 4) {
            return new ArrayList<>();
        }
        return nSum(nums, target, 4, new HashSet<>(), 0);
    }

    public List<List<Integer>> nSum(int[] nums, int target, int n, Set<Integer> used, int startIndex) {
        // 出口
        if (n == 2) {
            List<List<Integer>> res = new ArrayList<>();
            Map<Integer, Boolean> map = new HashMap<>();
            for (int i = startIndex; i < nums.length; i++) {
                int curr = nums[i];
                if (used.contains(curr)) {
                    continue;
                }
                if (map.containsKey(curr) && map.get(curr)) {
                    res.add(new ArrayList<>(Arrays.asList(target - curr, curr)));
                    map.put(curr, false);
                    map.put(target - curr, false);
                } else {
                    if (!map.containsKey(target - curr)) {
                        map.put(target - curr, true);
                    }
                }
            }
            return res;
        }

        // 递归
        List<List<Integer>> res = new ArrayList<>();
        for (int i = startIndex; i < nums.length - n + 1; i++) {
            int curr = nums[i];
            if (used.contains(curr)) {
                continue;
            } else {
                List<List<Integer>> resThisTerm = nSum(nums, target - curr, n - 1, new HashSet<>(used), i + 1);
                for (List<Integer> list : resThisTerm) {
                    list.add(curr);
                }
                res.addAll(resThisTerm);
            }
            used.add(curr);
        }
        return res;

    }

}
